#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import json
import glob
import pathlib
import lxml.etree
from common_python import check_package_installed


# mirrors
if True:
    check_package_installed({
        "gentoo": [
            "net-misc/mirrors",
        ],
    })

    print("/etc/mirrors/main.conf")
    for fullfn in glob.glob("/etc/mirrors/*.conf"):
        print(fullfn)
    print("/var/lib/mirrors")
    print("/var/log/mirrors")


# plugins
for fullfn in glob.glob("/usr/lib64/mirrors/plugins/*/metadata.xml"):
    pluginName = os.path.basename(os.path.dirname(fullfn))
    cfgFile = "/etc/mirrors/plugin-%s.conf" % (pluginName)

    pkgInfo = {
        "gentoo": [
            "net-misc/mirrors-plugin-%s" % (pluginName),
        ],
    }
    if not check_package_installed(pkgInfo, exit_or_return=False) or not os.path.exists(cfgFile):
        continue

    cfgData = {}
    if True:
        buf = pathlib.Path(cfgFile).read_text()
        if buf != "":
            cfgData = json.loads(buf)

    msIdList = []
    if True:
        rootElem = lxml.etree.parse(fullfn).getroot()
        if rootElem.tag == "mirror-site":
            msIdList.append(rootElem.get("id"))
        elif rootElem.tag == "mirror-site-factory":
            assert False
        elif rootElem.tag == "mirror-sites":
            for child in rootElem.xpath("./mirror-site"):
                msIdList.append(child.get("id"))

    print(cfgFile)
    for msId in msIdList:
        if "persist" in cfgData or "persist" in cfgData.get(msId, {}):
            print("/var/lib/mirrors/%s/***" % (msId))
        else:
            print("/var/cache/mirrors/%s/***" % (msId))
        print("/var/log/mirrors/mirror-site-%s/***" % (msId))
